package work.xiaohong.mina.test1;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.FilterEvent;

import java.util.Date;

/**
 * @author Kevin
 * @data 4/25/2022 11:19 AM
 * @description 自定义处理类
 **/
public class MyHandler extends IoHandlerAdapter {

  @Override
  public void sessionCreated(IoSession session) throws Exception {
    System.out.println("连接创建");
    super.sessionCreated(session);
  }

  @Override
  public void sessionOpened(IoSession session) throws Exception {
    System.out.println("连接打开");
    super.sessionOpened(session);
  }

  @Override
  public void sessionClosed(IoSession session) throws Exception {
    System.out.println("连接关闭");
    super.sessionClosed(session);
  }

  @Override
  public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    System.out.println("加入空闲状态");
    super.sessionIdle(session, status);
  }

  @Override
  public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    System.out.println("发生异常");
    super.exceptionCaught(session, cause);
  }

  @Override
  public void messageReceived(IoSession session, Object message) throws Exception {
    System.out.println("收到了消息---->"+message);
    String msg = new Date().toString()+"接收到了消息"+message;
    if ("exit".equals(message.toString())){
      System.out.println("收到退出指令");
      session.closeNow();
    }
//    session.write(msg);

    super.messageReceived(session, message);
  }

  @Override
  public void messageSent(IoSession session, Object message) throws Exception {
    System.out.println("发送了消息--->"+message);
    super.messageSent(session, message);
  }

  @Override
  public void inputClosed(IoSession session) throws Exception {
    System.out.println("输入关闭");
    super.inputClosed(session);
  }

  @Override
  public void event(IoSession session, FilterEvent event) throws Exception {
    super.event(session, event);
  }
}
